<?php

namespace Lib\DB;

if (! defined ( 'LIB' )) {
	exit ();
}
class DB {
	private $_aType = array (
			'Mysql',
			'Sqlite' 
	);
	private $_sDefault = 'Mysql';

	public function __construct() {
		$this->init ();
	}

	public function init($aConf = null, $sName = 'db') {
		if ($aConf == null) {
			$aConf = ( array )\Lib\o ()->Config->get ( 'db' );
		}
		if ($aConf) {
			$aConf ['type'] = ucfirst ( $aConf ['type'] ? $aConf ['type'] : 'mysql' );
			if ($sName == 'db') {
				$this->setDefault ( $aConf ['type'] );
			}
			$aConf ['slave'] = $aConf ['slave'] ? true : false;
			require_once __DIR__ . '/' . $aConf ['type'] . '.class.php';
			$sClass = __NAMESPACE__ . '\\' . $aConf ['type'];
			$this->__set ( $aConf ['type'], new $sClass ( $aConf ) );
			return true;
		} else {
			return false;
		}
	}

	public function setDefault($sType) {
		if (in_array ( ucfirst ( $sType ), $this->_aType )) {
			$this->_sDefault = ucfirst ( $sType );
		}
	}

	public function __call($sName, $aParam) {
		if ($aParam [0] ['type']) {
			$this->setDefault ( $aParam [0] ['type'] );
			$sType = ucfirst ( $aParam [0] ['type'] );
		} else {
			$sType = $this->_sDefault;
		}
		if (! $this->$sType) {
			$this->init ();
		}
		return call_user_func_array ( array (
				$this->$sType,
				$sName 
		), $aParam );
	}

	public function __get($sName) {
		if (! in_array ( $sName, $this->_aType )) {
			$sName = $this->_sDefault;
		}
		if (! $this->$sName) {
			$this->init ();
		}
		return $this->$sName;
	}

	public function __set($sName, $sValue) {
		$this->$sName = $sValue;
	}
}

?>